<?php

namespace app\index\controller;

use app\common\model\Company as CompanyModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\SpecialTopicEnroll as SpecialTopicEnrollModel;
use app\common\model\SpecialTopicRecruit as SpecialTopicRecruitModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserVip as UserVipModel;
use think\facade\Db;
use think\facade\View;

class SpecialTopic extends Base
{
    public function index()
    {
        $title = input('get.title', '');
        $data = SpecialTopicRecruitModel::whereLike('title', $title . '%')
            ->where('status', 1)
            ->order(['sort' => 'ASC', 'view' => 'DESC'])
            ->select();
        View::assign('special', $data);
        return view();
    }

    public function detail($id)
    {
        $specialData = SpecialTopicRecruitModel::where('id', $id)->find();
        $specialData->company_sum = SpecialTopicEnrollModel::where(['special_id' => $id, 'status' => 1])
            ->count();
        $specialData->jobs_sum = JobsModel::alias('job')
            ->join('special_topic_enroll enroll', 'enroll.company_id=job.company_id')
            ->where(['enroll.special_id' => $id, 'enroll.status' => 1])
            ->count();
        $specialData->resume_sum = JobsDeliveryResumeModel::alias('delivery')
            ->join('special_topic_enroll enroll', 'enroll.company_id=delivery.company_id')
            ->where(['enroll.special_id' => $id, 'enroll.status' => 1])
            ->group('delivery.resume_id')
            ->count();
        View::assign('special', $specialData);
        $companyData = SpecialTopicEnrollModel::alias('enroll')
            ->join('company company', 'company.id=enroll.company_id')
            ->join('company_industry industry', 'industry.id=company.industry_id')
            ->join('status_alias size_type', 'company.size_type=size_type.value')
            ->field(['company.*', 'size_type.title' => 'size_type', 'industry.title' => 'industry'])
            ->where('enroll.special_id', $id)
            ->where('enroll.status', 1)
            ->where('size_type.alias', 'company/size_type')
            ->order(['enroll.sort'=>'ASC', 'enroll.create_time'=>'DESC'])
            ->select();
        for ($i = 0; $i < count($companyData); $i++) {
            $item = $companyData[$i];
            $resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item->id])->count();
            $not_resume_sum = JobsDeliveryResumeModel::where(['company_id' => $item->id, 'status' => 0])->count();
            $companyData[$i]->resume_efficiency = ($resume_sum - $not_resume_sum) > 0 ? round(($resume_sum - $not_resume_sum) / $resume_sum * 100) : 0;
            $companyData[$i]->jobs_sum = JobsModel::where(['company_id' => $item->id, 'status' => 1])->count();
        }
        View::assign('companyList', $companyData);
        SpecialTopicRecruitModel::where('id', $id)
            ->inc('view')
            ->update();
        return view();
    }

    public function addEnroll()
    {
        $specialId = input('post.id');
        $special = SpecialTopicRecruitModel::where('id', $specialId)->find();
        if (empty($special)) {
            return $this->ajaxReturn('专题不存在！', -100);
        }
        if ($special->status != 1) {
            return $this->ajaxReturn('目标专题不是启用状态！', -100);
        }
        if ($special->end_time < time() || $special->start_time > time()) {
            return $this->ajaxReturn('此专题不在报名时间段，无法报名');
        }
        $user = session('User');
        if (empty($user)) {
            return $this->ajaxReturn('请先登录企业账号再报名！', -100);
        }
        if ($user['role_type'] != 1) {
            return $this->ajaxReturn('只有企业用户需要报名！', -100);
        }
        $company = CompanyModel::where('uid', $user['id'])->find();
        if (empty($company)) {
            return $this->ajaxReturn('请先绑定企业！', -100);
        }
        $existsEnroll = SpecialTopicEnrollModel::where(['special_id' => $special->id, 'company_id' => $company->id])->find();
        if ($existsEnroll) {
            if ($existsEnroll->status == 0) {
                return $this->ajaxReturn('你已报名，但未被管理员通过，请勿重复报名', -100);
            } else {
                return $this->ajaxReturn('你已报名，且已通过，请勿重复报名', -100);
            }
        }
        $userInfo = UserInfoModel::where('uid', $user['id'])->find();
        if ($userInfo->score < $special->point_cost) {
            return $this->ajaxReturn('报名需要扣除' . $special->point_cost . '积分，你的积分不足！');
        }
        $enrollNumber = SpecialTopicEnrollModel::where('special_id', $special->id)->count();
        if ($enrollNumber >= $special->max_limit) {
            return $this->ajaxReturn('此专题招聘企业报名名额已满，不能再继续报名', -100);
        }
        $vipLevels = explode(',', $special['vip_level']);
        $userVip = UserVipModel::where('uid', $user['id'])->find();

        if (!in_array($userVip->company_vip_level, $vipLevels)) {
            return $this->ajaxReturn('会员类型不在允许报名列表', -100);
        }
        // if ($userVip->company_vip_time >= time()) {
        //     return $this->ajaxReturn('你的会员权益已过期', -100);
        // }
        try {
            Db::startTrans();
            // 条件均满足，扣除积分，写入报名表
            $userInfo->dec('score', $special->point_cost)->save();
            $enroll = [
                'special_id' => $special->id,
                'company_id' => $company->id,
                'status' => 0
            ];
            SpecialTopicEnrollModel::create($enroll);
            Db::commit();
        } catch (\Throwable $ex) {
            Db::rollback();
            return $this->ajaxReturn('无法创建报名数据，积分已返还');
        }
        return $this->ajaxReturn('报名成功！');
    }
}
